class AnimSprite extends Sprite
{
  var _animSpec;
  int _currentFrame = 1;
  int _currentAnimFrames = 1;
  bool _playing = false;
  String _currAnim = "";
  bool _repeat = true;
  int animDelay, remainingTime;
  
  static final int DEFAULT_ANIM_DELAY = 17;
  
  AnimSprite(var spec):super(spec['src'])
  {
    _animSpec = spec;
    animDelay = DEFAULT_ANIM_DELAY;
    remainingTime = animDelay;
  }
  
  int get width()
  {
    if(_animSpec['frameWidth'] == null)
    {
      return super.width;
    }
    else return _animSpec["frameWidth"].toInt();
  }
  
  int get height()
  {
    if(_animSpec['frameHeight'] == null)
    {
      return super.height;
    }
    else return _animSpec["frameHeight"].toInt();
  }
  
  void setAnim(String anim)
  {
    this._currAnim = anim;
    this._currentFrame = 0;
    this._currentAnimFrames = _animSpec[anim].length;
  }
  
  void play(bool toPlay)
  {
    if(toPlay)
    {
      assert(_currAnim != null);
    }
    _playing = toPlay;
  }
  
  bool get isPlaying()
  {
    return _playing;
  }
  
  void update(int time)
  {
    if(_playing)
    {
      remainingTime -= time;
      if(remainingTime <= 0)
      {
        remainingTime = animDelay;
        if(_repeat)
        {
          this._currentFrame = (this._currentFrame + 1) % this._currentAnimFrames;
        }
        else
        {
          this._currentFrame++;
          if(this._currentFrame + 1 == this._currentAnimFrames)
          {
            play(false);
          }
        }
      }
    }
  }
  
  void draw()
  {
    CanvasWindow parentCanvas = getParentCanvas();
    num sx = 0;
    num sy = 0;
    num sw = this.width;
    num sh = this.height;
    num dx = getX();
    num dy = getY();
    num dw = sw;
    num dh = sh;
    
    num frameWidth = this._animSpec["frameWidth"];
    num frameHeight = this._animSpec["frameHeight"];
    
    if(_currAnim != "")
    {
      sx = frameWidth * this._animSpec[_currAnim][_currentFrame][1];
      sy = frameHeight * this._animSpec[_currAnim][_currentFrame][0];
      sw = this._animSpec["frameWidth"];
      sh = this._animSpec["frameHeight"];
      dw = sw;
      dh = sh;
    }

    parentCanvas.context.drawImageFromRect(this.element, sx, sy, sw, sh, dx, dy, dw, dh); 
    
  }
}
